package org.saxion.concurrency

import scala.actors.Actor
import scala.actors.Actor._
import java.util.ArrayList

class Secretary(projectLeader: Actor) extends Actor {
  var customersForMeeting: Int = 0;
  var developersForMeeting: Int = 0;
  val MAX_CUSTOMERS_MEETING: Int = 3;
  val MAX_DEVELOPERS_MEETING: Int = 2;
  val customerList = new ArrayList[Actor]
  val developerList = new ArrayList[Actor]
  var hasMeeting = false;
  
  def act() {
    loop {
      receive {
        case AskForMeeting =>
          if (sender.isInstanceOf[Customer]) {
            handleCustomer();
          } else if (sender.isInstanceOf[Developer]) {
            handleDeveloper();
          }
        case EndMeeting(clearCustomerList: Boolean) =>
          handleEndMeeting(clearCustomerList);
      }
    }
  }

  def handleCustomer() {
    if (!(customersForMeeting == MAX_CUSTOMERS_MEETING) && !hasMeeting) {
      sender ! WaitForMeeting
      customersForMeeting += 1;
      println(sender.asInstanceOf[Customer].getName + " has been added " + customersForMeeting)
      customerList.add(sender.asInstanceOf[Customer]);
      if (customersForMeeting == MAX_CUSTOMERS_MEETING) {
        hasMeeting = true;
        println("--Customer Meeting Beginning--")
        projectLeader ! CustomerMeeting(customerList)
      }
    } else {
      sender ! WaitForMeeting
      sender ! CastAway
    }
  }

  def handleDeveloper() {
    if (!(developersForMeeting == MAX_DEVELOPERS_MEETING) && !hasMeeting) {
      sender ! WaitForMeeting
      developersForMeeting += 1;
      println(sender.asInstanceOf[Developer].getName + " has been added: " + developersForMeeting)
      developerList.add(sender.asInstanceOf[Developer]);
      if (developersForMeeting == MAX_DEVELOPERS_MEETING) {
        hasMeeting = true;
        println("--Developer Meeting Beginning--")
        projectLeader ! DeveloperMeeting(developerList)
        var it = developerList.iterator
        while (it.hasNext()) {
          it.next ! BeginMeeting
        }
      }
    } else {
      sender ! WaitForMeeting
      sender ! GoBackToWork
    }
  }

  def handleEndMeeting(clearCustomerList: Boolean) {
    if (sender.isInstanceOf[ProjectLeader]) {
      if (clearCustomerList) {
        customerList.clear();
        customersForMeeting = 0;
      }
      hasMeeting = false;
      developerList.clear();
      developersForMeeting = 0;
      println("**Meeting has ended**")
    }
  }
}